package com.ray.service;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.poi.ss.formula.functions.T;
import org.apache.xmlbeans.impl.jam.mutable.MPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;

import com.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGUpdateStatement;
import com.fasterxml.jackson.annotation.ObjectIdGenerators.StringIdGenerator;
import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.google.appengine.api.search.query.QueryParser.andOp_return;
import com.google.appengine.api.search.query.QueryParser.restriction_return;
import com.google.apphosting.utils.remoteapi.RemoteApiPb.Request;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CompanyMaterialTypeBean;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.GradeBean;
import com.ray.bean.PurchaseDetailBean;
import com.ray.bean.PurchaseOrderBean;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.ShoppingMallMapper;
import com.ray.pojo.MyUser;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.util.CreateIdUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.sun.mail.mbox.Mailbox;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ShoppingMallService {
	
	@Autowired
	ShoppingMallMapper shoppingMallMapper;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
    @Autowired
    CompanyService companyService;
    @Autowired
    UserService userService;
    @Autowired
    PlatformTransactionManager platformTransactionManager;
    @Autowired
    CompanyMaterialService companyMaterialService;
    @Autowired
    PurchaseOrderService purchaseOrderService;
    
   
	/**
	 * @isUrl true
	 * 通过选择物料发布到商城
	 * materialArray  物料json数组
	 * 选择物料的时候，其他属性等同于物料  数量(count)   单价(unitPrice) 为填写值
	 * @return
	 */
	public String addShoppingCallMaterialBySelected(Map map) {
		StringUtil.checkIsTrue(map, "materialArray", "未获取到物料信息");
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		String jsonStr=map.get("materialArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(jsonStr);
		List<CompanyMaterialTableBean> materialList=(List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArray, CompanyMaterialTableBean.class);
		Set<String> materialCodeSet=materialList.stream().map(CompanyMaterialTableBean::getMaterialCode).collect(Collectors.toSet());
		Assert.isTrue(materialCodeSet.size()>0,"请选择导入物料");
		Set<String> repaitSet=shoppingMallMapper.checkRepaitMaterialCode(materialCodeSet,myUser.getCompany());
		Assert.isTrue(null==repaitSet || repaitSet.size()<=0,"有重复物料");
		materialList.forEach(cc->{
			cc.setCompany(myUser.getCompany());
			cc.setCreater(myUser.getUserId());
			cc.setStatus("0");
			if(this.checkImgSetStatus(cc)) {
				cc.setStatus("1");
			}
			int row=shoppingMallMapper.insertShoppingCallMaterial(cc);
			basicDataService.synImgsToBaidu(cc, myUser, ReturnStringUtil.SHOPPING_IMG_TAG);
			Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		});
		return ReturnStringUtil.ADD_SUCCESS;
	}
	
	/**
	 * 根据有没有图片设置物料状态
	 * @param cc
	 * @return
	 */
	private boolean checkImgSetStatus(CompanyMaterialTableBean cc) {
		if(null!=cc.getImg() && !"".equals(cc.getImg())) {
			return true;
		}
		if(null!=cc.getImgFour() && !"".equals(cc.getImgFour())) {
			return true;
		}
		if(null!=cc.getImgThree() && !"".equals(cc.getImgThree())) {
			return true;
		}
		if(null!=cc.getImgTwo() && !"".equals(cc.getImgTwo())) {
			return true;
		}
		return false;
	}

	/**
	 * 新发布物料
	 * @isUrl true
	 * @param map
	 * materialName(物料名称)
	 * model(规格型号)
	 * unit(单位)
	 * unitPrice(单价)
	 * defaultWarehouse 仓位
	 * materialType 物料类型
	 * color 色号
	 * colorDescription 色号描述
	 * providerNo 编号(供方编号)
	 * providerName 编号(供方编号)
	 * procurementCycles 采购周期
	 * img(图片1)
	 * imgTwo(图片2)
	 * imgThree(图片3)
	 * imgFour(图片4)
	 * typeId (分类id)
	 * isSynchronization (是否同步库存 1 同步 2 不同步)
	 * @return
	 * @throws Exception 
	 */
	
	public String addShoppingCallNew(Map map) throws Exception{
		StringUtil.checkIsTrue(map, "materialName", "未获取到物料名称");
		StringUtil.checkIsTrue(map, "model", "未获取到规格型号");
		StringUtil.checkIsTrue(map, "unit", "未获取到单位");
		StringUtil.checkNotNull(map, "unitPrice", "未获取到单价");
		StringUtil.checkIsTrue(map, "defaultWarehouse", "未获取到仓位类型");
		StringUtil.checkIsTrue(map, "providerName", "未获取到厂家");
		StringUtil.checkNotNull(map, "color", "未获取到色号");
		StringUtil.checkNotNull(map, "colorDescription", "未获取到色号描述");
		StringUtil.checkNotNull(map, "providerNo", "未获取到供方编号");
		StringUtil.checkNotNull(map, "img", "未获取到图片1");
		StringUtil.checkNotNull(map, "imgTwo", "未获取到图片2");
		StringUtil.checkNotNull(map, "imgThree", "未获取到图片3");
		StringUtil.checkNotNull(map, "imgFour", "未获取到图片4");
		StringUtil.checkNotNull(map, "typeId", "未获取到分类id");
		StringUtil.checkNotNull(map, "procurementCycles", "未获取到采购周期");
		StringUtil.checkNotNull(map, "isSynchronization", "未获取到是否同步库存");
		CompanyMaterialTableBean companyMaterialTableBean=(CompanyMaterialTableBean) this.mapToObject(map, CompanyMaterialTableBean.class);
		Assert.notNull(companyMaterialTableBean,"转换异常");
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		companyMaterialTableBean.setStatus("使用");
		this.createNewTransaction((o)->{
        	 List<CompanyMaterialTableBean> materialList=basicDataService.insertCompanyMaterial(companyMaterialTableBean,myUser);
        	 return materialList.get(0);
        },companyMaterialTableBean);
		companyMaterialTableBean.setCreater(map.get("loginUserId").toString());
		companyMaterialTableBean.setCompany(map.get("loginCompany").toString());
		companyMaterialTableBean.setStatus("0");
		//校验图片
		if(this.checkImgSetStatus(companyMaterialTableBean)) {
			companyMaterialTableBean.setStatus("1");
		}
		//插入公司物料表失败，没有返回物料代码,设置物料代码
		if("".equals(companyMaterialTableBean.getMaterialCode())) {
			List<CompanyMaterialTableBean> cclist=shoppingMallMapper.getShoppingCallMaterialByMaterialCodeAndCompany(companyMaterialTableBean.getMaterialCode(), companyMaterialTableBean.getCompany(), ReturnStringUtil.COMPANY_MATERIAL_NAME);
		    if(null!=cclist && cclist.size()>0) {
		    	companyMaterialTableBean.setMaterialCode(cclist.get(0).getMaterialCode());
		    }
		}
		List<CompanyMaterialTableBean> materialLists=new ArrayList<CompanyMaterialTableBean>();
		materialLists.add(companyMaterialTableBean);
		Set<String> repaitSet=this.getCompanyMaterialRepeatId(materialLists,ReturnStringUtil.SHOPPING_CALL_MATERIAL);
		Assert.isTrue(repaitSet.size()<=0,"已存在此物料，不可重复添加");
		int row=shoppingMallMapper.insertShoppingCallMaterial(companyMaterialTableBean);
		basicDataService.synImgsToBaidu(companyMaterialTableBean, myUser, ReturnStringUtil.SHOPPING_IMG_TAG);
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
	}
	

	/**
	 * 调用方法时重新开启一个事务
	 * @param function
	 * @param object
	 */
	public  void createNewTransaction(Function function,Object object) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
        TransactionStatus status = platformTransactionManager.getTransaction(def);
        try {
        	function.apply(object);
            platformTransactionManager.commit(status);
        } catch (Exception ex) {
        	ex.printStackTrace();
        	System.out.println("出现异常，事务回滚");
            try {
            	platformTransactionManager.rollback(status);
            } catch (TransactionException trEx){
               System.out.println("回滚失败");
            }
        }
	}
	
	
	/**
	 * 将map装换为对象
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public   Object mapToObject(Map map, Class<?> beanClass) throws Exception {    
	       if (map == null) {
	    	   return null;  
	       }
	      Object obj = beanClass.newInstance();  
	      BeanUtils.populate(obj, map);  
	      return obj;  
	 }    
	
	/**
	 * @isUrl true
	 * start 分页参数
	 * length 分页参数
	 * 获取公司发布物料详情
	 */
	public DatatablesViewPageBean<CompanyMaterialTableBean> getShoppingCallMaterialData(Map map){
		DatatablesViewPageBean<CompanyMaterialTableBean> datatablesViewPageBean=new DatatablesViewPageBean<CompanyMaterialTableBean>();
		//获取公司发布的物料信息
		List<CompanyMaterialTableBean> list=shoppingMallMapper.getShoppingCallMaterialData(map);
		int count=shoppingMallMapper.getShoppingCallMaterialDataCount(map);
	    list=this.setContact(list);
		datatablesViewPageBean.setReturnData(list);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		return datatablesViewPageBean;
	}
	
	/**
	 * @isUrl true
	 * idArray id集合
	 * @param map
	 * @return
	 */
	public List<CompanyMaterialTableBean> getShoppingCallCompanyByIds(Map map){
		StringUtil.checkIsTrue(map, "idArray", "未获取到id参数集合");
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		Map paramMap=new HashMap();
		paramMap.put("idList", idList);
		paramMap.put("status", 1);
 		List<CompanyMaterialTableBean> list=shoppingMallMapper.getShoppingCallMaterialData(paramMap);
	    list=this.setContact(list);
	    return list;
	}
	
	

	/**
	 * 设置联系人和联系方式
	 * @param list
	 * @return
	 */
	private List<CompanyMaterialTableBean> setContact(List<CompanyMaterialTableBean> list) {
		if(null==list) {return list;}
		Set<String> companySet=list.stream().filter(o->"".equals(o.getContactName())).map(CompanyMaterialTableBean::getCompany).collect(Collectors.toSet());
		//如果有物料的发布人被禁用了，就要查找公司设置的商城联系人
		if(companySet.size()>0) {
			List<UserBean> userList= shoppingMallMapper.getManyCompanyShoppingContact(companySet);
			if(null==userList) {userList=new ArrayList<UserBean>();}
			Map<String, List<UserBean>> companyUserMap=userList.stream().collect(Collectors.groupingBy(UserBean::getCompany));
		    for(CompanyMaterialTableBean companyMaterialTableBean:list) {
		    	if("".equals(companyMaterialTableBean.getContactName())) {
		    		List<UserBean> xx=companyUserMap.get(companyMaterialTableBean.getCompany());
		    		if(null!=xx) {
		    			companyMaterialTableBean.setContactName(xx.get(0).getUserName());
		    			companyMaterialTableBean.setContactPhone(xx.get(0).getPhone());
		    		}
		    	}
		    }
		}
		return list;
	}

	/**
	 * @isUrl true
	 * start 分页参数
	 * length 分页参数
	 * 获取所有公司发布的物料
	 */
	public DatatablesViewPageBean<CompanyMaterialTableBean> getAllShoppingCallMaterialData(Map map){
		map.put("myCompany", map.get("loginCompany"));//将登录公司设为我的公司，在关联收藏记录的时候可以看到
		map.put("loginCompany", null);//不需要登录公司,因为不止查本公司的记录
		map.put("company", map.get("providerName"));//按供应商搜索的时候，就是物料的公司
		map.put("status", 1);//只搜索没下架的物料
		map.put("providerName", null);//供应的屏蔽
		map.put("isLogin", "notIsLogin");//loginCompany是否为本公司
		return this.getShoppingCallMaterialData(map);
	}
	
	
	
	/**
	 * @isUrl true
	 * start 分页参数
	 * length 分页参数
	 * company 查询的公司名称
	 * 获取所有公司发布的物料
	 */
	public DatatablesViewPageBean<CompanyMaterialTableBean> getOneCompanyMaterial(Map map){
		StringUtil.checkIsTrue(map, "company", "未获取到公司名称");
		map.put("myCompany", map.get("loginCompany"));//将登录公司设为我的公司，在关联收藏记录的时候可以看到
		map.put("loginCompany", map.get("company"));//将要查询的公司设为登录公司
		map.remove("company");
		map.put("status", 1);//只搜索没下架的物料
		map.put("isLogin", "notIsLogin");//loginCompany是否为本公司
		return this.getShoppingCallMaterialData(map);
	}
	
	
	/**
	 * @isUrl true 
	 * 修改商城物料
	 * 传入的参数视为修改 不传的视为不修改
	 * id 主键
	 * @return
	 * @throws Exception 
	 */
	public String updateShoppingCallMaterial(Map map) throws Exception {
		StringUtil.checkIsTrue(map, "id", "未获取到物料");
		CompanyMaterialTableBean companyMaterialTableBean =(CompanyMaterialTableBean) this.mapToObject(map, CompanyMaterialTableBean.class);	
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		//校验图片
		if("1".equals(companyMaterialTableBean.getStatus())) {
			Assert.isTrue(this.checkImgSetStatus(companyMaterialTableBean),"上架物料必须有图片，要清除图片请先下架");
			//图片同步百度
			this.synImg(myUser,companyMaterialTableBean);
		}
		companyMaterialTableBean.setCompany(myUser.getCompany());
		companyMaterialTableBean.setLastModifier(myUser.getUserId());
		//校验是否有四要素相同,id不同的物料的物料
		int count=shoppingMallMapper.getFourParamEquealMaterialButNotEqualId(companyMaterialTableBean);
		Assert.isTrue(count<=0,"已存在相同的物料，不可重复修改");
		int row=shoppingMallMapper.updateShoppingCallMaterial(companyMaterialTableBean);
		Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
		//修改公司物料表
		myUser.setIsUpdate(ReturnStringUtil.SHOPPING_CALL_UPDATE_MATERIAL);
		List<CompanyMaterialTableBean> cclist=shoppingMallMapper.getShoppingCallMaterialByMaterialCodeAndCompany(companyMaterialTableBean.getMaterialCode(), companyMaterialTableBean.getCompany(), ReturnStringUtil.COMPANY_MATERIAL_NAME);
	    //如果公司物料表存在物料
		if(null==cclist|| cclist.size()<=0) {
			return ReturnStringUtil.UPDATE_SUCCESS;
		}
		companyMaterialTableBean.setId(cclist.get(0).getId());
		basicDataService.updateCompanyMaterial(companyMaterialTableBean,myUser);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
	
	/**
	 * 来自于公司物料表修改商城物料
	 * @return
	 * @throws Exception 
	 */
	public boolean updateMaterialFromCompanyMaterial(CompanyMaterialTableBean companyMaterialTableBean,MyUser myUser) throws Exception {
		if(ReturnStringUtil.SHOPPING_CALL_UPDATE_MATERIAL.equals(myUser.getIsUpdate())) {
			myUser.setIsUpdate("");
			return true;
		}
		List<CompanyMaterialTableBean> list=shoppingMallMapper.getShoppingCallMaterialByMaterialCodeAndCompany(companyMaterialTableBean.getMaterialCode(),myUser.getCompany(),ReturnStringUtil.SHOPPING_CALL_MATERIAL);
		//如果物料没有导入到商城
		if(null==list || list.size()<=0) {
			return true;
		}
		CompanyMaterialTableBean shoppMaterial=list.get(0);
		companyMaterialTableBean.setLastModifier(myUser.getUserId());
		companyMaterialTableBean.setCompany(myUser.getCompany());
		companyMaterialTableBean.setId(shoppMaterial.getId());
		//校验图片
		if("1".equals(shoppMaterial.getStatus())) {
			Assert.isTrue(this.checkImgSetStatus(companyMaterialTableBean),"上架物料必须有图片，要清除图片请先下架");
			//图片同步百度
			this.synImg(myUser,companyMaterialTableBean);
		}
		//校验是否有四要素相同,id不同的物料的物料
		int count=shoppingMallMapper.getFourParamEquealMaterialButNotEqualId(companyMaterialTableBean);
		Assert.isTrue(count<=0,"已存在相同的物料，不可重复修改");
		int row=shoppingMallMapper.updateShoppingCallMaterial(companyMaterialTableBean);
		Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
		return true;
	}
	
	

	/**
	 * 将图片同步到百度
	 * @param myUser
	 * @throws Exception 
	 */
	private void synImg(MyUser myUser,CompanyMaterialTableBean companyMaterialTableBean) throws Exception {
	     basicDataService.synImgsToBaidu(companyMaterialTableBean, myUser, ReturnStringUtil.SHOPPING_IMG_TAG);
	}

	/**
	 * @isUrl true
	 * idArray id集合字符串
	 * status 2下架  1 上架(恢复)
	 * 上下架物料
	 * @param map
	 * @return
	 */
	public String offShoppingCallMaterial(Map map) { 
		StringUtil.checkIsTrue(map, "idArray", "未获取到下架id集合");
		String idsStr=map.get("idArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(idsStr);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		Assert.isTrue(idList.size()>0,"未获取到id集合");
		map.put("idList", idList);
		int row=shoppingMallMapper.offShoppingCallMaterial(map);
		this.synAllImg(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	
	/**
	 * 批量同步百度图片
	 * @param map
	 */
	private void synAllImg(Map map) {
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		Map paramMap=new HashMap<>();
		paramMap.put("idList", map.get("idList"));
		List<CompanyMaterialTableBean> list=shoppingMallMapper.getShoppingCallMaterialData(paramMap);
		int status=Integer.parseInt(map.get("status").toString());
		//上架
		if(1==status) {
			for(CompanyMaterialTableBean companyMaterialTableBean:list) {
				Assert.isTrue(this.checkImgSetStatus(companyMaterialTableBean),"无图片不可上架");
				basicDataService.synImgsToBaidu(companyMaterialTableBean, myUser, ReturnStringUtil.SHOPPING_IMG_TAG);
			}
		}else {//下架
			for(CompanyMaterialTableBean companyMaterialTableBean:list) {
				companyMaterialTableBean.setImg(null);
				companyMaterialTableBean.setImgFour(null);
				companyMaterialTableBean.setImgThree(null);
				companyMaterialTableBean.setImgTwo(null);
				basicDataService.synImgsToBaidu(companyMaterialTableBean, myUser, ReturnStringUtil.SHOPPING_IMG_TAG);
			}
		}
		
	}

	/**
	 * 批量插入商城导入物料记录
	 * @param notRepeatList
	 * @return
	 */
	private int addImportRecord(List<CompanyMaterialTableBean> notRepeatList) {
		int row=shoppingMallMapper.addImportRecord(notRepeatList);
		return row;
	}

	/**
	 * 移除收藏记录
	 * 2 代表移除记录  3 代表已导入至本公司
	 */
	private int removeCollectionRecord(List<String> shoppingCallMaterialIdList, String loginCompany,int status) {
		int row=shoppingMallMapper.updateCollectionStatus(shoppingCallMaterialIdList,loginCompany,status);
		return row;
	}
	
	

	/**
	 * 获取公司所有供应商
	 * @param map
	 * @return
	 */
	private List<CustomerBean> getCompanyCustomer(Map map) {
		Map getCustomerMap=new HashMap();
		getCustomerMap.put("type", 1);
		getCustomerMap.put("status", "使用");
		getCustomerMap.put("loginCompany", map.get("loginCompany"));
		List<CustomerBean> list=basicDataService.getCustomerList(getCustomerMap);
		if(null==list) {list=new ArrayList<CustomerBean>();}
		return list;
	}

	/**
	 * 获取和公司物料表重复的id
	 * 物料类型必须要有五个属性(物料名称，规格，色号，供应商，公司)
	 * @param materialTableBeans
	 * @return
	 */
	private Set<String> getCompanyMaterialRepeatId(List<CompanyMaterialTableBean> materialTableBeans,String tableName) {
		Set<String> list=shoppingMallMapper.getRepeatMaterialDetail(materialTableBeans,tableName);
		if(list==null) {list=new HashSet<String>();}
		list=list.stream().filter(ss->!"".equals(ss)).collect(Collectors.toSet());
		return list;
	}
	

    /**
     * @isUrl true
     * 获取所有填过的厂家
     * @param map
     * @return
     */
    public Set<String> getAllFactoryName(Map map){
    	return shoppingMallMapper.getAllFactoryName();
    }
    
    /**
     * @isUrl true
     * 将商城的物料导入到本公司
     * id (商城物料id)
     * @param map
     * @return
     * @throws IOException 
     * @throws ServiceException 
     */
    public String importShoppingMaterialToMyCompany(Map map) throws ServiceException, IOException {
    	StringUtil.checkIsTrue(map, "id", "未获取到id");
    	String id =map.get("id").toString();
    	CompanyMaterialTableBean companyMaterialTableBean=shoppingMallMapper.getShoppingCallMaterialById(id);
    	Assert.notNull(companyMaterialTableBean,"物料不存在");
        this.chekCustomer(companyMaterialTableBean.getProviderName(), map);
        companyMaterialTableBean.setCompany(map.get("loginCompany").toString());
        companyMaterialTableBean.setMaterialCode(basicDataService.setCompanyMaterialCode(companyMaterialTableBean.getProviderName(), companyMaterialTableBean.getMaterialName()));
        companyMaterialTableBean.setStatus("使用");
        companyMaterialTableBean.setMaterialType("");//将物料类型设为空
        List<CompanyMaterialTableBean> list=new ArrayList<CompanyMaterialTableBean>();
    	list.add(companyMaterialTableBean);
    	Set<String> repearIdSet=this.getCompanyMaterialRepeatId(list,ReturnStringUtil.COMPANY_MATERIAL_NAME);
    	Assert.isTrue(repearIdSet.size()<=0,"物料已存在");
    	//插入到本公司物料表
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		Boolean bool=companyMaterialService.addWarehouseForShopByBatch(myUser,list);
		Assert.isTrue(bool,ReturnStringUtil.ADD_ERROR);
		//保存导入记录
		int addRow=this.addImportRecord(list);
		Assert.isTrue(addRow>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
    }
    
    
    /**
     * 从商城直接采购物料
     * id 商城物料主键
     * purchaseCount  采购数量
     * @param map
     * @return
     * @throws ParseException 
     * @throws IOException 
     * @throws ServiceException 
     */
    public String purchaseShoppingCallMaterial(Map map) throws ParseException, ServiceException, IOException {
    	StringUtil.checkIsTrue(map, "id", "未获取到id");
    	String  id=map.get("id").toString();
    	CompanyMaterialTableBean companyMaterialTableBean=shoppingMallMapper.getShoppingCallMaterialById(id);
    	Assert.notNull(companyMaterialTableBean,"物料不存在");
    	List<CompanyMaterialTableBean> companyMaterialList=this.getCompanyMaterialListByFourParam(companyMaterialTableBean,map);
    	CompanyBean companyBean=this.getCompany(companyMaterialTableBean.getCompany());
    	CompanyMaterialTableBean cmb=null;
    	//公司物料表不存在这种记录的话
    	if(null!=companyMaterialList && companyMaterialList.size()<=0) {
    		this.chekCustomer(companyMaterialTableBean.getProviderName(), map);
    		companyMaterialTableBean.setMaterialCode(basicDataService.setCompanyMaterialCode(companyMaterialTableBean.getProviderName(), companyMaterialTableBean.getMaterialName()));
    		companyMaterialTableBean.setMaterialType("");//物料类型设为空
    		companyMaterialTableBean.setStatus("使用");
    		List<CompanyMaterialTableBean> list=new ArrayList<CompanyMaterialTableBean>();
        	list.add(companyMaterialTableBean);
        	//插入到本公司物料表
    		HttpServletRequest request=(HttpServletRequest) map.get("request");
    		MyUser myUser=RequestUtil.getLoginUser(request);
        	Boolean bool=companyMaterialService.addWarehouseForShopByBatch(myUser,list);
    		Assert.isTrue(bool,ReturnStringUtil.ADD_ERROR);
    		cmb=companyMaterialTableBean;
    	}else {//如果公司物料表已存在记录
    		cmb=companyMaterialList.get(0);
        }
    	String returStr =this.savePurchaseStack(cmb,companyBean,map);
    	return returStr;
    }
   
    
    /**
     * 保存采购单信息
     * @param cmb 物料信息
     * @param companyBean 公司信息
     * @param map 采购数量,采购单id
     * @return
     * @throws ParseException 
     */
    private String savePurchaseStack(CompanyMaterialTableBean cmb, CompanyBean companyBean, Map map) throws ParseException {
    	PurchaseOrderBean purchaseOrderBean=new PurchaseOrderBean();
    	purchaseOrderBean.setPurchasePeople(map.get("loginUserId").toString());
    	purchaseOrderBean.setProviderName(companyBean.getCompanyName());//供应商为公司名称（经销商）
    	purchaseOrderBean.setCurrency(ReturnStringUtil.SHOPPINT_CALL_PURCHASE_CURRENCY);
    	purchaseOrderBean.setType(2);
    	purchaseOrderBean.setStatus(0);
    	purchaseOrderBean.setAgent(companyBean.getId());
    	purchaseOrderBean.setAgentSource(2);//商城来源
    	List<PurchaseDetailBean> detailList=new ArrayList<PurchaseDetailBean>();
    	PurchaseDetailBean purchaseDetailBean=new PurchaseDetailBean();
    	purchaseDetailBean.setPrice(cmb.getUnitPrice());
    	purchaseDetailBean.setTax(ReturnStringUtil.SHOPPINT_CALL_PURCHASE_TAX);
    	purchaseDetailBean.setMaterialCode(cmb.getMaterialCode());
    	purchaseDetailBean.setPurchaseCount(Double.parseDouble(map.get("purchaseCount").toString()));
    	purchaseDetailBean.setProcurementCycles(cmb.getProcurementCycles());
    	purchaseDetailBean.setMaterialName(cmb.getMaterialName());
    	purchaseDetailBean.setModel(cmb.getModel());
    	purchaseDetailBean.setColor(cmb.getColor());
    	purchaseDetailBean.setColorDescription(cmb.getColorDescription());
    	detailList.add(purchaseDetailBean);
    	purchaseOrderBean.setDetailList(detailList);
    	List<PurchaseOrderBean> list=new ArrayList<PurchaseOrderBean>();
    	list.add(purchaseOrderBean);
    	JSONArray jsonObject=JSONArray.fromObject(purchaseOrderBean);
    	map.put("purchase", jsonObject.toString());
    	String returStr=purchaseOrderService.savePurchaseStack(map);
		return returStr;
	}

	/**
     * 根据公司名称获取公司信息
     * @param company
     * @return
     */
    private CompanyBean getCompany(String company) {
    	Map map=new HashMap();
    	map.put("loginCompany", company);
		return companyService.getCompany(map);
	}

	/**
     * 通过四要素获取公司物料表信息
     * @param companyMaterialTableBean
     * @return
     */
    private List<CompanyMaterialTableBean> getCompanyMaterialListByFourParam(
			CompanyMaterialTableBean companyMaterialTableBean,Map map) {
    	Map paramMap=new HashMap();
    	paramMap.put("loginCompany", map.get("loginCompany"));
    	paramMap.put("materialName", companyMaterialTableBean.getMaterialName());
    	paramMap.put("model", companyMaterialTableBean.getModel());
    	paramMap.put("color", companyMaterialTableBean.getColor());
    	paramMap.put("providerName", companyMaterialTableBean.getProviderName());
		return companyMaterialService.getCompanyMaterialByMap(paramMap);
	}

	/**
   	 * 校验供应商
   	 * @param materialCompany(物料所属公司)
   	 * @param map
   	 */
   	private void chekCustomer(String materialCompany, Map map) {
   		HttpServletRequest request=(HttpServletRequest) map.get("request");
   		MyUser myUser=RequestUtil.getLoginUser(request);
   		CompanyBean companyInfo=shoppingMallMapper.getCompanyManagerUser(materialCompany);
   		companyInfo=companyInfo==null?new CompanyBean():companyInfo;
   		String customerCode=basicDataService.getPYIndexStr(materialCompany+companyInfo.getId(), true);
   		CustomerBean customerBean=new CustomerBean();
   		customerBean.setCustomerCode(customerCode);
   		customerBean.setCustomerName(materialCompany);
   		customerBean.setStatus("使用");
   		customerBean.setContact(companyInfo.getName());
   		customerBean.setAddress(companyInfo.getAddress());
   		customerBean.setEmail(companyInfo.getEmail());
   		customerBean.setFax(companyInfo.getFax());
   		customerBean.setPhone(companyInfo.getPhone());
   		customerBean.setType(1);
   		this.createNewTransaction((o)->{basicDataService.insertCustomer(customerBean, myUser); return o;}, null);
   	}
   	
   	/**
   	 * 获取公司联系人信息
   	 */
   	public  CompanyBean getCompanyManagerUser(String companyName) {
   		return  shoppingMallMapper.getCompanyManagerUser(companyName); 
   	}
    
   	/**
   	 * @isUrl true
   	 * 获取从商城导入到本公司物料记录
   	 * @param map
   	 * @return
   	 */
   	public  DatatablesViewPageBean<CompanyMaterialTableBean> getShoppingCallImportToCompanyRecord(Map map){
   		DatatablesViewPageBean<CompanyMaterialTableBean> datatablesViewPageBean=new DatatablesViewPageBean<CompanyMaterialTableBean>();
		//获取公司发布的物料信息
		List<CompanyMaterialTableBean> list=shoppingMallMapper.getShoppingCallImportToCompanyRecord(map);
		int count=shoppingMallMapper.getShoppingCallImportToCompanyRecordCount(map);
		datatablesViewPageBean.setReturnData(list);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		return datatablesViewPageBean;
   	}
   	
   	/**
   	 * @isUrl true 
   	 * 从收藏物料记录中采购物料
   	 * materialCode  物料代码
   	 * agent 经销商
   	 * purchaseCount 采购数量
   	 * @param map
   	 * @return
   	 * @throws ParseException 
   	 */
   	public String purchaseImportRecordMaterial(Map map) throws ParseException {
   		StringUtil.checkIsTrue(map, "materialCode", "未获取到物料代码");
   		StringUtil.checkIsTrue(map, "agent", "未获取到经销商");
   		StringUtil.checkIsTrue(map, "agent", "未获取到经销商");
   		CompanyMaterialTableBean companyMaterialTableBean=this.getCompanyMaterialByMaterialCodeAndCompanyName(map);
   		CompanyBean companyBean=this.getCompany(map.get("agent").toString());
   		String returnStr=this.savePurchaseStack(companyMaterialTableBean, companyBean, map);
   		return returnStr;
   	}
    
   	/**
   	 * 获取公司物料信息，通过物料代码和公司
   	 * @param map
   	 * @return
   	 */
   	private CompanyMaterialTableBean getCompanyMaterialByMaterialCodeAndCompanyName(Map map) {
   		Map paramMap=new HashMap();
   		paramMap.put("materialCode", map.get("materialCode"));
   		paramMap.put("loginCompany", map.get("loginCompany"));
   		List<CompanyMaterialTableBean> list=companyMaterialService.getCompanyMaterialByMap(paramMap);
   		Assert.isTrue(null!=list && list.size()>0,"物料不存在");
   		return list.get(0);
   	}
   	
   	/**
   	 * @isUrl true
   	 * 获取物料分组信息
   	 */
   	public List<GradeBean> getShoppingCallMaterialType(Map map){
		return shoppingMallMapper.getShoppingCallMaterialType(map);
   	}
   	
   	
    /**
     * @isUrl true
     * 获取采购我家物料的采购单信息
     * start 分页参数
     * length 分页参数
     * @param map
     * @return
     */
    public DatatablesViewPageBean<PurchaseOrderDetailPojo> getAllPurchaseMyCompanyMaterial(Map map){
    	Map purchaseMap=this.getPurchaseMap(map);
    	return purchaseOrderService.getPurchaseOrderByPageFromShoppingCall(purchaseMap);
    }

    /**
     * 获取采购单信息参数
     * @param map
     * @return
     */
	private Map getPurchaseMap(Map map) {
		Map purchaseMap=new HashMap();
		purchaseMap.put("agent", map.get("loginCompanyId"));
		purchaseMap.put("status", 1);
		purchaseMap.put("start", map.get("start"));
		purchaseMap.put("length", map.get("length"));
		if(null != map.get("company")) {
			map.put("loginCompany", map.get("company"));
		}
		return purchaseMap;
	}
	
	/**
	 * @isUrl true
	 * 设置商城联系人
	 * idArray 用户id集合
	 * @return
	 */
	public String setShoppingCallContactUser(Map map) {
		StringUtil.checkIsTrue(map, "idArray", "未获取到用户id");
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray =JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		int deleteRow =shoppingMallMapper.deleteContactByCompanyName(map);
		map.put("idList", idList);
		int addRow=shoppingMallMapper.addShoppingContact(map);
		return ReturnStringUtil.SET_SUCCESS;
	}
	
	/**
	 * 获取商城联系人
	 * @param map
	 * @return
	 */
	public List<UserBean> getShoppingCallContactUser(Map map){
		return shoppingMallMapper.getShoppingCallContactUser(map);
	}
	
	/**
	 * 获取所有在商城发布物料的公司
	 * @param map
	 * @return
	 */
    public List<CompanyBean> getAllShoppingCallCompany(Map map){
	   return shoppingMallMapper.getAllShoppingCallCompany();
    }
	
    
    /**
     * @isUrl true
     * 获取可以导入到商城的物料
     * @param map
     * @return
     */
    public  DatatablesViewPageBean<CompanyMaterialTableBean> getCanImportShoppingCallMaterial(Map map){
    	DatatablesViewPageBean<CompanyMaterialTableBean> datatablesViewPageBean=new DatatablesViewPageBean<CompanyMaterialTableBean>();
    	List<CompanyMaterialTableBean> list=shoppingMallMapper.getCanImportShoppingCallMaterial(map);
    	int count=shoppingMallMapper.getCanImportShoppingCallMaterialCount(map);
    	datatablesViewPageBean.setReturnData(list);
    	datatablesViewPageBean.setiTotalDisplayRecords(count);
    	datatablesViewPageBean.setiTotalRecords(count);
    	return datatablesViewPageBean;
    }
   	
    /**
     ***********************************************以下方法全部作废********************************************************
     */
    
    


	/**
	 * 作废   收藏夹已经没有了
	 * @isUrl true
	 * start 分页参数
	 * length 分页参数
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<CompanyMaterialTableBean> getCollectionMaterialData(Map map){
		DatatablesViewPageBean<CompanyMaterialTableBean> datatablesViewPageBean=new DatatablesViewPageBean<CompanyMaterialTableBean>();
	    List<CompanyMaterialTableBean> collectionList=shoppingMallMapper.getCollectionMaterialData(map);
	    collectionList=this.setSuppilerIsReleationConpany(map.get("loginCompany").toString(), collectionList);
	    int count=shoppingMallMapper.getCollectionMaterialDataCount(map);
		datatablesViewPageBean.setReturnData(collectionList);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		return datatablesViewPageBean;
	}
	
	/**
	 * 作废  取消关联关系
	 * 设置物料的公司是否被关联到本公司
	 * @param company
	 * @param list
	 * @return
	 */
	private List<CompanyMaterialTableBean> setSuppilerIsReleationConpany(String company, List<CompanyMaterialTableBean> list) {
		Map map=new HashMap();
		map.put("loginCompany", company);
		List<CustomerBean> customerBeans=this.getCompanyCustomer(map);
		Set<String> linkCompanySet=customerBeans.stream().map(CustomerBean::getLinkCompany).collect(Collectors.toSet());
		list.forEach(material->{
			material.setSuppilerIsReleationConpany(linkCompanySet.contains(material.getCompany()));
		});
		return list;
	}
    
    /**
	 * 作废  没有批量导入
	 * @isUrl true 
	 * materialArray 物料集合
	 * 将收藏中的物料导入到本公司
	 * @param map
	 * @return
	 * @throws IOException 
	 * @throws ServiceException 
	 */
	public String importMaterialToCompany(Map map) throws ServiceException, IOException {
		StringUtil.checkIsTrue(map, "materialArray", "未获取到物料信息");
		String materialStr=map.get("materialArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(materialStr);
		List<CompanyMaterialTableBean> materialTableBeans=(List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArray, CompanyMaterialTableBean.class);
		Assert.isTrue(null!=materialTableBeans && materialTableBeans.size()>0,"未获取到物料信息");
		Assert.isTrue(materialTableBeans.size()<=100,"一次最多可以导入100条");
		String loginCompany=map.get("loginCompany").toString();
		//获取公司所有供应商
		List<CustomerBean> customerBeans=this.getCompanyCustomer(map);
		Set<String> customerNameSet=customerBeans.stream().map(CustomerBean::getCustomerName).collect(Collectors.toSet());
		//供应商设置为物料公司，公司设置为登录人公司
		materialTableBeans.forEach(material->{
			Assert.isTrue(customerNameSet.contains(material.getProviderName()),material.getProviderName()+"在本公司供应商表不存在,请先添加");
			material.setCompany(loginCompany);
		});
		//获取与公司物料表
		Set<String> repearIdSet=this.getCompanyMaterialRepeatId(materialTableBeans,ReturnStringUtil.COMPANY_MATERIAL_NAME);
		//获取与公司物料表里不重复的数据
		List<CompanyMaterialTableBean> notRepeatList=materialTableBeans.stream().filter(mm->!repearIdSet.contains(mm.getId())).collect(Collectors.toList());
		//设置物料代码
		notRepeatList.forEach(material->{
			material.setMaterialCode(basicDataService.setCompanyMaterialCode(material.getProviderName(), material.getMaterialName()));
		});
		//插入到本公司物料表
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		Boolean bool=companyMaterialService.addWarehouseForShopByBatch(myUser,notRepeatList);
		Assert.isTrue(bool,ReturnStringUtil.ADD_ERROR);
		//移除收藏夹
		List<String> idList=notRepeatList.stream().map(CompanyMaterialTableBean::getId).collect(Collectors.toList());
		int removeRow=this.removeCollectionRecord(idList,loginCompany,ReturnStringUtil.SHOPPING_CALL_COLLECTION_STATUS_IMPORT);
		Assert.isTrue(removeRow>0,ReturnStringUtil.ADD_ERROR);
		//保存导入记录
		int addRow=this.addImportRecord(notRepeatList);
		Assert.isTrue(addRow>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
	}
    
    /**
	 * 作废  收藏夹已经没有了
	 * 移除收藏夹中的物料
	 * idArray 商城物料id
	 * @param map
	 * @return
	 */
	public String removeCollection(Map map) {
		StringUtil.checkIsTrue(map, "idArray", "未获取到物料id");
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		String loginCompany=map.get("loginCompany").toString();
		int row=this.removeCollectionRecord(idList,loginCompany,ReturnStringUtil.SHOPPING_CALL_COLLECTION_STATUS_DELETE);
		Assert.isTrue(row>0,ReturnStringUtil.DELETE_ERROR);
		return ReturnStringUtil.DELETE_SUCCESS;
	}
	
	
    /**
	 * 作废   不再有批量导入
	 * @isUrl true 
	 * materialArray 物料集合
	 * 校验要导入的物料是否存在于本公司
	 * @param map
	 * @return
	 */
	public List<CompanyMaterialTableBean> checkImportMaterialIsRepeat(Map map) {
		StringUtil.checkIsTrue(map, "materialArray", "未获取到物料信息");
		String materialStr=map.get("materialArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(materialStr);
		List<CompanyMaterialTableBean> materialTableBeans=(List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArray, CompanyMaterialTableBean.class);
		Assert.isTrue(null!=materialTableBeans && materialTableBeans.size()>0,"未获取到物料信息");
		Assert.isTrue(materialTableBeans.size()<=100,"一次最多可以导入100条");
		String loginCompany=map.get("loginCompany").toString();
		//获取公司所有供应商
		List<CustomerBean> customerBeans=this.getCompanyCustomer(map);
		Set<String> customerNameSet=customerBeans.stream().map(CustomerBean::getCustomerName).collect(Collectors.toSet());
		//供应商设置为物料公司，公司设置为登录人公司
		materialTableBeans.forEach(material->{
			Assert.isTrue(customerNameSet.contains(material.getProviderName()),material.getProviderName()+"在本公司供应商表不存在，请先添加");
			material.setCompany(loginCompany);
		});
		Set<String> repearIdSet=this.getCompanyMaterialRepeatId(materialTableBeans,ReturnStringUtil.COMPANY_MATERIAL_NAME);
		materialTableBeans.forEach(material->{
			material.setIsRepeat(repearIdSet.contains(material.getId()));
		});
		return materialTableBeans;
	}
    
    
    /**
	 * 作废，物料类型不作为物料必须属性
	 * 校验物料类型
	 * @param shoppingMaterial(商城物料信息)
	 * @param map
	 */
	private void checkMaterialType(CompanyMaterialTableBean shoppingMaterial, Map map) {
		Map materialMap=new HashMap<>();
		materialMap.put("loginCompany", map.get("loginCompany"));
		materialMap.put("materialType", shoppingMaterial.getMaterialType());
		//materialMap.put("status", 1);
		List<CompanyMaterialTypeBean> materialTypeList=companyMaterialTypeService.getCompanyMaterialTypeListData(map);
		//如果本公司已存在此物料类型
		if(null!=materialTypeList && materialTypeList.size()>0) {
			CompanyMaterialTypeBean companyMaterialTypeBean=materialTypeList.get(0);
			//如果公司物料类型是读颜色的，但商城物料不带色号
			if(companyMaterialTypeBean.getIsReadColor()==1) {
				if(shoppingMaterial.getColor()==null || "".equals(shoppingMaterial.getColor())) {
//					Assert.isTrue(1==2,"要读颜色但没有颜色咋搞嘞？");
				}
			}
		}else {//如果本公司没有此物料类型,根据物料是否带色号判断此类型读不读颜色
			if(shoppingMaterial.getColor()==null || "".equals(shoppingMaterial.getColor())){
				materialMap.put("isReadColor", 2);
			}else {
				materialMap.put("isReadColor", 1);
			}
			if("辅料仓".equals(shoppingMaterial.getDefaultWarehouse()) || "辅料".equals(shoppingMaterial.getDefaultWarehouse())) {
				materialMap.put("defaultWarehouse", 2);
			}else {
				materialMap.put("defaultWarehouse", 1);
			}
			materialMap.put("isSelfAdded", 1);//本公司添加
			materialMap.put("loginUserId", map.get("loginUserId"));
			materialMap.put("status", 1);
			materialMap.put("createOrderIsShow", 1);//在制单页面显示
			companyMaterialTypeService.addCompanyMaterialType(materialMap);
		}
	}
    
    /**
	 * 作废
	 * @isUrl true
	 * 加入收藏夹
	 * @param map
	 * @return
	 */
	public String collectionShoppingMaterial(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		//校验此物料是否被公司收藏过
		List<String> haveList=shoppingMallMapper.getCollectionShoppingMaterialRecordById(map);
		Assert.isTrue(null==haveList || haveList.size()<=0,"该物料已收藏过");
		int row=shoppingMallMapper.addCollectionShoppingMaterialRecord(map);
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		return  ReturnStringUtil.ADD_SUCCESS;
	}
    
    /**
	 * @isUrl true
	 * 关联公司    作废
	 * linkCompany 关联公司名
	 * id 供应商id
	 * @param map
	 * @return
	 */
	public String relationSuppilerAndCompany(Map map) {
		StringUtil.checkIsTrue(map, "linkCompany", "未获取到关联公司");
		StringUtil.checkIsTrue(map, "id", "未获取到供应商id");
		List<CustomerBean> customerBeans=this.getCompanyCustomer(map);
		String linkCompany=map.get("linkCompany").toString();
		String id=map.get("id").toString();
		List<CustomerBean> releationList=customerBeans.stream().filter(cc->cc.getLinkCompany().equals(linkCompany)).collect(Collectors.toList());
		if(releationList.size()>0) {
			Assert.isTrue(releationList.size()<=0,linkCompany+"已关联本厂供应商："+releationList.get(0).getCustomerName());
		}
		releationList=customerBeans.stream().filter(cc->cc.getId().equals(id)).collect(Collectors.toList());
		Assert.isTrue(releationList.size()>0,"供应商不存在");
		Map companyMap=new HashMap();
		companyMap.put("loginCompany", map.get("linkCompany"));
		CompanyBean companyBean=companyService.getCompany(companyMap);
		Assert.notNull(companyBean!=null,map.get("linkCompany").toString()+"不存在");
		int row=basicDataService.updateCustomerForLinkCompany(map);
		Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
    
    /**
	 * 作废  取消关联
	 * 将商场发布物料的公司导入到本公司为供应商
	 * linkCompany
	 * 其他参数等等同于添加供应商
	 * @param map
	 * @return
	 * @throws Exception 
	 */
    public String importShoppingCallCompanyToSuppiler(Map map) throws Exception {
    	StringUtil.checkIsTrue(map, "linkCompany", "未获取到关联公司");
    	List<CustomerBean> customerBeans=this.getCompanyCustomer(map);
    	CustomerBean customerBean=(CustomerBean) this.mapToObject(map, CustomerBean.class);
    	List<CustomerBean> releationList=customerBeans.stream().filter(cc->cc.getLinkCompany().equals(customerBean.getLinkCompany())).collect(Collectors.toList());
    	if(releationList.size()>0) {
    		Assert.isTrue(releationList.size()<=0,customerBean.getLinkCompany()+"已关联本厂供应商："+releationList.get(0).getCustomerName());
    	}
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		MyUser myUser=RequestUtil.getLoginUser(request);
		basicDataService.insertCustomer(customerBean, myUser);
	    return ReturnStringUtil.ADD_SUCCESS;
    }
    
}
